package com.mali.backendcommon.util;

import com.mali.backendcommon.properties.EmailProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Data
@AllArgsConstructor
@Slf4j
public class EmailUtil {


    private String host;
    private long port;
    private String userName;
    private String password;

    private  String IsAuth;

    private  String IsTls;

    public  void sendEmail(String to, String subject, String content) {
        // 配置邮件服务器信息
        Properties properties = new Properties();
        properties.put("mail.smtp.host",host); // 邮件服务器地址
        properties.put("mail.smtp.port", port); // 邮件服务器端口
        properties.put("mail.smtp.auth", IsAuth); // 开启认证
        properties.put("mail.smtp.starttls.enable", IsTls); // 开启TLS加密


        // 创建邮件会话
        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        });

        try {
            // 创建邮件消息
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(userName));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject);
            message.setText(content);

            // 发送邮件
            Transport.send(message);
            log.info("邮件发送成功");
        } catch (MessagingException e) {
            throw new RuntimeException("邮件发送失败"+e.getMessage());
        }
    }

}
